<template>
  <div ref="container" style="height:100%;text-align: left;"></div>
</template>
<script>
import * as monaco from "monaco-editor";
export default {
  $monacoEditor: null,
  props: {
    sourceVersion: {
      type: String,
      default: ''
    },
    targetVersion: {
      type: String,
      default: ''
    },
    language: {
      type: String,
      default: "html"
    },
    theme: {
      type: String,
      default: "vs"
    },
    editorOptions: {
      type: Object,
      default: function () {
        return {
          selectOnLineNumbers: true,
          roundedSelection: false,
          cursorStyle: "line", //光标样式
          automaticLayout: true, //自动布局
          glyphMargin: true, //字形边缘
          useTabStops: false,
          fontSize: 28, //字体大小
          autoIndent: true //自动缩进
          //quickSuggestionsDelay: 500,   //代码提示延时
        };
      }
    }
  },
  data() {
    return {
      themeOption: [
        {
          value: "vs",
          label: "默认"
        },
        {
          value: "hc-black",
          label: "高亮"
        },
        {
          value: "vs-dark",
          label: "深色"
        }
      ],
      original: null,
      modified: null
    };
  },
  computed: {
    originalModel() {
      if (this.original)
        return this.original;
      this.original = monaco.editor.createModel(this.sourceVerion, this.language);
      return this.original;
    },
    modifiedModel() {
      if (this.modified)
        return this.modified;
      this.modified = monaco.editor.createModel(this.targetVerion, this.language);
      return this.modified;
    }
  },
  watch: {
    options: {
      deep: true,
      handler(options) {
        this.$monacoEditor.updateOptions(options);
      }
    },

    sourceVersion(newValue) {
      this.originalModel.setValue(newValue);
    },
    targetVersion(newValue) {
      this.modifiedModel.setValue(newValue);
    },
    language(newVal) {
      this.$monacoEditor.setModelLanguage(this.$monacoEditor.getModel(), newVal);
    },
    theme(newVal) {
      this.$monacoEditor.setTheme(newVal);
    }
  },
  created() {
    this.$nextTick(() => {
      this.initEditor();
    });
  },
  beforeDestroy() {
    this.$monacoEditor && this.$monacoEditor.dispose();
  },

  methods: {
    initEditor() {
      this.$el.innerHTML = "";
      this.$monacoEditor = monaco.editor.createDiffEditor(this.$el, {
        //language: this.language,
        theme: this.theme, //vs, hc-black, or vs-dark
        automaticLayout: true,
        readOnly: true,
        editorOptions: this.editorOptions
      });

      this.$monacoEditor.setModel({
        original: this.originalModel,
        modified: this.modifiedModel
      });

      var layout = this.$minifox.debounce(this.layout, 200);

      layout();

      this.$emit("onMounted", this.$monacoEditor); //编辑器创建完成回调

    },
    layout() {
      this.$monacoEditor.layout();
    }
  }
};
</script>
